
var QQMapWX = require('utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var websocket = require('utils/js/websocket.js');
var utils = require('utils/util.js');
var protobuf = require('weichatPb/protobuf.js'); //引入protobuf模块
var HallLoginMessage = require('utils/js/SentBody.js');//加载awesome.proto对应的json
//require('utils/js/js/message.js');
//require('utils/js/js/replybody.js');
//require('utils/js/js/sentbody.js');
//require('utils/js/cim.web.sdk.js');
//app.js
let that
App({
  onLaunch: function() {
   that = this;
   // CIMPushManager.connect();
 this.globalData.userInfo

    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'IV2BZ-WUZ3P-XSXDC-VSZOH-XLKOV-QMF34'
    });
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    this.login();
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
    // 获取系统状态栏信息
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
         	this.globalData.Custom = capsule;
        	this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
        	this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })

    this.getUserLocation();
  },
  globalData: {
    token:'',
    userInfo: null,
    lat:'',
    lng:'',
    currentLocation:'',
    address:'',
  domain:'https://api.luozejiao.com/renren-api/api',
   // domain: 'http://localhost:8081/renren-api/api',
  //  domain2: 'http://localhost:8080',
    domain2: 'https://chat.luozejiao.com',
    placeId:0,
    wxxx: 0,
    chatList:[],
    chatCount:0,
    callback: function () { },
    callbackLogin: function () { },
  },

  login:function()
  {
  
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log("res.code:")
        if (res.code) {
          //发起网络请求
          wx.request({
            url: this.globalData.domain + '/cxcLogin',
            data: {
              code: res.code,
              appId:'',//个人测试传appid
              secret: '',//个人测试传secret
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded '
            },
            method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            success: function (res) {
              if (res.data.code!=0)
              {
                wx.showToast({
                  title: `登录失败：${res.data.msg}`,
                  icon: "none",
                  duration: 2000
                })
                return
              }
              console.log("loginRes:", res);
              that.globalData.token = res.data.token;
              that.globalData.userInfo = res.data.user
              console.log(" that.globalData.userInfo", that.globalData.userInfo)
              that.globalData.callbackLogin();
              //调通接口
              websocket.connect(that.globalData.userInfo, function (res) {
                console.log("websocket.connect", res)
                var data = websocket.receiveMessage(res.data)
                console.log("data.data1", data)
                if (data.receiver) {

           
                  that.globalData.callback(data);
              
             
                }
              })
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }


    })
  },

  //监听通讯
  watchChat: function (method) {
    var obj = this.globalData;
    Object.defineProperty(obj, "chatCount", { //这里的 data 对应 上面 globalData 中的 data

      configurable: true,
      enumerable: true,
      set: function (value) { //动态赋值，传递对象，为 globalData 中对应变量赋值
        console.log("value", value)
        this._chatCount= value;
        method(value);
      },
      get: function () { //获取全局变量值，直接返回全部
        ///  return this.globalData;
        return this._chatCount
      }
    })
  },

  // 判断用户是否拒绝地理位置信息授权，拒绝的话重新请求授权
  getUserLocation: function () {
    let that = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      that.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          that.getLocation();
        }
        else {
          //调用wx.getLocation的API
          that.getLocation();
        }
      }
    })
  },
  // 获取定位当前位置的经纬度
  getLocation: function () {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log("wx.getLocation",res)
        let latitude = res.latitude
        let longitude = res.longitude
        that.globalData.lat = res.latitude;//
        that.globalData.lng = res.longitude;//把onload定位时候的经纬度存到全局
        let speed = res.speed
        let accuracy = res.accuracy;
        that.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let that = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log("getLocal",res)
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district;
        // 保存一下当前定位的位置留着后面重新定位的时候搜索附近地址用
        that.globalData.currentLocation = district;
        that.globalData.address = res.result.address;

      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  char2buf: function(str) {
    var out = new ArrayBuffer(str.length)
  var u8a = new Uint8Array(out)
  var strs = str.split("")
  for(var i = 0; i<strs.length; i++) {
  u8a[i] = strs[i].charCodeAt()
}
return out
}
,
})